package cn.group7.padserver.controller;

import cn.group7.padserver.common.Flag;
import cn.group7.padserver.controller.responseformat.Code;
import cn.group7.padserver.controller.responseformat.Result;
import cn.group7.padserver.entity.MyPurchase;
import cn.group7.padserver.entity.PurchaseDetail;
import cn.group7.padserver.entity.SellPurchase;
import cn.group7.padserver.entity.ShoppingModel;
import cn.group7.padserver.pojo.Purchase;
import cn.group7.padserver.pojo.ShoppingCart;
import cn.group7.padserver.service.PurchaseDetailService;
import cn.group7.padserver.service.PurchaseService;
import cn.group7.padserver.service.SellPurchaseService;
import cn.group7.padserver.service.ShoppingCartService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @author 谷汉斌
 * @description 购物车模块
 * @createTime 2024/8/4 下午3:20
 */
@RestController
@RequestMapping("/carts")
@Api(tags = "购物车接口")
public class ShoppingCartController {

    @Autowired
    private ShoppingCartService shoppingcartService;

    @Autowired
    private PurchaseService purchaseService;

    @Autowired
    private PurchaseDetailService purchaseDetailService;

    @Autowired
    private SellPurchaseService sellPurchaseService;

    /**
     * 添加商品到购物车
     *
     * @param id 商品id
     */
    @ApiOperation("添加商品到购物车")
    @PostMapping("/add/{id}")
    public Result add(@PathVariable("id") Integer id) {
        //获取登陆的用户名
        UserDetails principal = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String name = principal.getUsername();
        ShoppingCart shoppingcart = new ShoppingCart();
        shoppingcart.setOwnName(name);
        shoppingcart.setOrderId(id);
        shoppingcart.setCount(1);
        shoppingcart.setCreateTime(new Date());
        shoppingcart.setUpdateTime(new Date());
        List<ShoppingModel> shoppingcarts = shoppingcartService.selectByUserOrderId(id);
        //没有购物车就添加、有就更新
        if (null != shoppingcarts && !shoppingcarts.isEmpty()) {
            shoppingcart.setCount(shoppingcarts.get(0).getCount() + 1);
            shoppingcart.setShoppingId(shoppingcarts.get(0).getShoppingId());
            shoppingcartService.update(shoppingcart);
        } else {
            shoppingcartService.add(shoppingcart);
        }
        return Result.builder().flag(Flag.SUCCESS.isCode())
                .message(Code.ADD_SUCCESS.getInfo())
                .code(Code.ADD_SUCCESS.getCode())
                .build();

    }


    /**
     * 从购物车删除商品
     *
     * @param id 商品id
     */
    @ApiOperation("从购物车删除商品")
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable("id") Integer id) {
        boolean delete = shoppingcartService.delete(id);
        return Result.builder().flag(delete ? Flag.SUCCESS.isCode() : Flag.FAIL.isCode())
                .message(delete ? Code.DELETE_SUCCESS.getInfo() : Code.DELETE_FAIL.getInfo())
                .code(delete ? Code.DELETE_SUCCESS.getCode() : Code.DELETE_FAIL.getCode())
                .build();
    }


    /**
     * 展示购物车列表
     */
    @ApiOperation("展示购物车列表")
    @GetMapping("/list")
    public Result list() {
        return Result.builder().flag(Flag.SUCCESS.isCode())
                .message(Code.QUERY_SUCCESS.getInfo())
                .code(Code.QUERY_SUCCESS.getCode())
                .data(shoppingcartService.selectByUsername())
                .build();
    }


    /**
     * 更新购物车商品数量
     */
    @ApiOperation("更新购物车商品数量")
    @PutMapping("/update/{id}/{count}")
    public Result update(@PathVariable("id") Integer id, @PathVariable("count") Integer count) {

        //创建实例ShoppingCart，设置id,数量，更新日期
        ShoppingCart shoppingcart = new ShoppingCart();
        shoppingcart.setShoppingId(id);
        shoppingcart.setCount(count);
        shoppingcart.setUpdateTime(new Date());
        //更新
        boolean update = shoppingcartService.update(shoppingcart);
        return Result.builder().flag(update ? Flag.SUCCESS.isCode() : Flag.FAIL.isCode())
                .message(update ? Code.UPDATE_SUCCESS.getInfo() : Code.UPDATE_FAIL.getInfo())
                .code(update ? Code.UPDATE_SUCCESS.getCode() : Code.UPDATE_FAIL.getCode())
                .build();

    }

    /**
     * 提交订单
     */
    @ApiOperation("提交订单")
    @PostMapping("/commitOrder/{addId}/{tMoney}")
    public Result commitOrder(@PathVariable("addId") Integer addId, @PathVariable("tMoney") String tMoney, @RequestBody List<ShoppingModel> shoppingModelList) {
        //获取登陆的用户名
        UserDetails principal = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String name = principal.getUsername();
        //添加购买人买入订单
        //创建Purchase实例，设置订单类型为
        Purchase purchase = new Purchase();
        //买入商品
        purchase.setPurchaseType(1);
        purchase.setOwnName(name);
        purchase.setAddress(addId.toString());
        //状态统一为待发货
        purchase.setPurchaseStatus(1);
        purchase.setTotalPrice(new BigDecimal(tMoney));
        purchase.setCreateTime(new Date());
        purchase.setUpdateTime(new Date());

        purchaseService.add(purchase);
        //取得刚才插入订单的id
        Purchase PurchaseGetId = purchaseService.selectNewPurchaseId(name);
        Integer purchaseId = PurchaseGetId.getPurchaseId();
        //添加购买人买入订单详细
        if (null != shoppingModelList && !shoppingModelList.isEmpty()) {
            PurchaseDetail purchaseDetail = new PurchaseDetail();
            SellPurchase sellPurchase = new SellPurchase();
            for (int i = 0; i < shoppingModelList.size(); i++) {
                ShoppingModel shoppingModel = shoppingModelList.get(i);
                purchaseDetail.setCount(shoppingModel.getCount());
                purchaseDetail.setOrderId(shoppingModel.getOrderId());
                purchaseDetail.setPurchaseId(purchaseId);
                purchaseDetail.setSumPrice(new BigDecimal(Double.parseDouble(shoppingModel.getPrice()) * shoppingModel.getCount()));
                purchaseDetail.setUninPrice(new BigDecimal(shoppingModel.getPrice()));
                purchaseDetailService.add(purchaseDetail);

                //卖出订单
                //添加卖出方卖出订单
                //创建Purchase实例，设置订单类型为
                sellPurchase.setOrderId(shoppingModel.getOrderId());
                sellPurchase.setAddress(addId.toString());
                sellPurchase.setOwnName(shoppingModel.getOwnName());
                sellPurchase.setPurchaseId(purchaseId);
                sellPurchase.setPurchaseStatus(1);
                sellPurchase.setPurchaseType(2);
                sellPurchase.setSumPrice(new BigDecimal(Double.parseDouble(shoppingModel.getPrice()) * shoppingModel.getCount()));
                sellPurchase.setUninPricee(new BigDecimal(shoppingModel.getPrice()));
                sellPurchase.setCreateTime(new Date());
                sellPurchase.setUpdateTime(new Date());
                sellPurchaseService.add(sellPurchase);
                //删除购物车信息
                shoppingcartService.delete(shoppingModel.getShoppingId());
            }
        }
        return new Result().builder().code(Code.ADD_SUCCESS.getCode())
                .flag(Flag.SUCCESS.isCode())
                .message(Code.ADD_SUCCESS.getInfo())
                .build();
    }


    /**
     * 根据登录用户查询我卖出的订单
     */
    @ApiOperation(value = "根据登录用户查询我卖出的订单")
    @GetMapping("/selectSells")
    public Result selectSells() {
        List<SellPurchase> purchase = sellPurchaseService.selectByName();
        return Result.builder().flag(Flag.SUCCESS.isCode())
                .code(Code.QUERY_SUCCESS.getCode())
                .data(purchase)
                .message(Code.QUERY_SUCCESS.getInfo()).build();

    }

    /**
     * 根据登录用户查询我买的订单
     */
    @ApiOperation(value = "根据登录用户查询我买的订单")
    @GetMapping("/selectBuys")
    public Result selectBuys() {
        List<MyPurchase> purchase = purchaseService.selectByPurchaseType();
        return Result.builder().code(Code.QUERY_SUCCESS.getCode()).flag(Flag.SUCCESS.isCode())
                .message(Code.QUERY_SUCCESS.getInfo()).data(purchase).build();
    }

    /**
     * 根据登录用户查询我买的订单详情
     */
    @ApiOperation(value = "根据登录用户查询我买的订单详情")
    @GetMapping("/selectBuysDetail/{id}")
    public Result selectBuysDetail(@PathVariable("id") Integer purchaseId) {
        List<PurchaseDetail> purchaseDetail = purchaseDetailService.selectByPurchaseId(purchaseId);
        return Result.builder().flag(Flag.SUCCESS.isCode()).flag(Flag.SUCCESS.isCode())
                .message(Code.QUERY_SUCCESS.getInfo()).data(purchaseDetail).build();
    }
}
